﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.ProOrderCommand;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.ProOrderCommandHandlers
{
    public class CreateProOrderCommandHandlers : IRequestHandler<CreateProOrderCommand, int>
    {

        private readonly IProOrderRepository _PRoOrder;

        private readonly IProOrderDetailRepository _proOrderDetail;
        private readonly IMapper _mapper;
        ISqlSugarClient db;


        public CreateProOrderCommandHandlers(IProOrderRepository proOrder, IProOrderDetailRepository proOrderDetail, IMapper mapper, ISqlSugarClient sqlSugarClient)
        {
            _PRoOrder = proOrder;
            _proOrderDetail = proOrderDetail;
            _mapper = mapper;
            db = sqlSugarClient;

        }

        public async Task<int> Handle(CreateProOrderCommand request, CancellationToken cancellationToken)
        {
            db.Ado.BeginTran();
            try
            {
                var order = _mapper.Map<ProduceOrders>(request.AddDto);
                var code = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                order.POrderNumber = $"SCDD{code}";
                var res = await _PRoOrder.AddAsync(order);

                foreach (var item in request.AddDto.DetailList)
                {
                    ProduceOrderDetail detail = new ProduceOrderDetail()
                    {
                        POId = order.POrderNumber,
                        PPId = item.PPId,
                        PCompletionDate = item.PCompletionDate,
                        PDeliveryDate = item.PDeliveryDate,
                        POrderNum = item.POrderNum,
                        ProductId = item.ProductId,
                        ProductionPlansId = item.ProductionPlansId,
                        ProductionType = item.ProductionType,
                        PStartTime = item.PStartTime,
                        AddName = item.AddName,
                        AddTime = item.AddTime,
                        Office_Id = item.Office_Id,
                        User_Id = item.User_Id,
                    };
                    var ressult = await _proOrderDetail.AddAsync(detail);
                }


                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
